<template>
  <div class="site-manage">
    <el-form :inline="true" :model="queryForm" class="demo-form-inline" style="text-align: right">
<!--      <el-form-item style="width: 180px">-->
<!--        <el-input v-model="queryForm.blurry" placeholder="请输入站点编码或名称"/>-->
<!--      </el-form-item>-->
<!--      <el-form-item>-->
<!--        <el-button type="primary" color="#3aecff" @click="search">搜索</el-button>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" color="#3aecff" @click="onAddStation">添加</el-button>
      </el-form-item>
      <el-form-item>
        <el-upload
          class="upload-demo"
          action="#"
          :auto-upload="false"
          :limit="1"
          :show-file-list="false"
          :on-change="handleChange"
        >
          <el-button type="primary" color="#3aecff">批量导入</el-button>
          <template #file="{ file }">
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" color="#3aecff" @click="downloadTemp">下载模板</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" color="#3aecff" @click="onUpgrade">更新软件</el-button>
      </el-form-item>
    </el-form>
    <el-scrollbar class="site-info" height="100%">
      <el-collapse v-model="activeNames" @change="handleColChange" accordion>
        <el-collapse-item v-for="item in siteTree" :title="item.name" :name="item.code">
          <template #title>
            <div style="width: 100%;">{{item.name}}
              <el-button @click.stop="onBatchUpdate(item)" style="margin-left: 20px" color="#3aecff" size="small">设备信息
              </el-button>
            </div>
          </template>
          <el-collapse v-model="childNames" style="padding-left: 30px" accordion>
            <el-collapse-item v-for="region in item.regions" :title="region.name" :name="region.code">
              <DataTable
                class="no-search-table-container"
                :hasIndex="true"
                :selection="false"
                :tableHead="tableHead"
                :tableData="region.stationInfoList"
                :isHasPagination="false"
                :border="false"
                @selection-change="handleSelectionChange">
                <template v-slot:pre>
                  <el-table-column
                    prop="id"
                    label="站点ID"
                    width="110"
                    align="left"
                  >
                    <template #default="scope">
                      <div class="dot" :style="{background:scope.row.online?'#3afc7b':'#f16565'}"></div>
                      <div class="element">{{ scope.row.id }}</div>
                    </template>
                  </el-table-column>
                </template>
<!--                <el-table-column-->
<!--                  prop="online"-->
<!--                  label="在线状态"-->
<!--                  width="90"-->
<!--                  align="center"-->
<!--                >-->
<!--                  <template #default="scope">-->
<!--                    <el-tag-->
<!--                      :type="scope.row.online ? 'success' : 'info'"-->
<!--                      disable-transitions-->
<!--                      effect="dark"-->
<!--                    >{{ scope.row.online ? '在线' : '离线' }}-->
<!--                    </el-tag>-->
<!--                  </template>-->
<!--                </el-table-column>-->
                <el-table-column
                  label="操作"
                  align="left"
                  width="160"
                  prop="roleName">
                  <template #default="scope">
                    <el-button
                      v-if="!scope.row.realStatus"
                      size="small" type="success"
                      @click="handleRealtime(scope.$index, scope.row,'realTime')">启动实时
                    </el-button>
                    <el-button
                      v-if="scope.row.realStatus===1"
                      size="small" type="primary"
                      @click="handleRealtime(scope.$index, scope.row,'realTime')">停止实时
                    </el-button>
                    <el-button
                      size="small" type="primary" color="#3aecff"
                      @click="handleRealtime(scope.$index, scope.row,'restart')">重启
                    </el-button>
                    <!-- <el-button
                      size="small" type="primary" color="#3aecff"
                      @click="handleRealtime(scope.$index, scope.row,'restart')">测试
                    </el-button> -->
                  </template>
                </el-table-column>
                <el-table-column
                  label="编辑"
                  align="left"
                  width="220"
                  prop="roleName">
                  <template #default="scope">
                    <el-button
                      size="small" type="primary"
                      @click="editDevice(scope.$index, scope.row)">设备信息
                    </el-button>
                    <el-button
                      size="small" type="primary"
                      @click="edit(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-popconfirm
                      confirm-button-text="确定"
                      cancel-button-text="取消"
                      icon-color="#626AEF"
                      title="确定要删除这个站点吗?"
                      @confirm="remove(scope.$index, scope.row)"
                    >
                      <template #reference>
                        <el-button size="small" type="danger">删除
                        </el-button>
                      </template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </DataTable>
            </el-collapse-item>
          </el-collapse>
        </el-collapse-item>
      </el-collapse>
    </el-scrollbar>
    <el-drawer
      v-model="showAddDialog"
      title="修改站点信息"
      :append-to-body="true"
      :direction="'ltr'"
      size="650px"
    >
      <SiteAddDialog :data="currentStation" v-if="showAddDialog" @refresh="getDatas"></SiteAddDialog>
    </el-drawer>
    <el-drawer
      v-model="showEditorDevice"
      :title="'设备信息（'+currentProvince.name+'）'"
      :append-to-body="true"
      :direction="'ltr'"
      size="650px"
    >
      <MqttEditorDilaog :data="currentProvince" v-if="showEditorDevice"/>
    </el-drawer>
    <el-drawer
      v-model="showEditorBase"
      :title="`设备信息 （${currentDevice.name} | ${currentDevice.id}）`"
      :append-to-body="true"
      :direction="'ltr'"
      size="650px"
    >
      <SingleDeviceDialog :data="currentDevice" v-if="showEditorBase"/>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import {onMounted, Ref, ref} from "vue";
  import {startRealtime, stopRealtime, reboot,realtimeControl,onlineControl} from "@/api/earthquake";
  import {deleteStation, pageStation, upgradeDevice, uploadExcel} from "@/api/site";
  import {siteTree,getTree,test} from "@/variable/Site";
  import MqttEditorDilaog from './comps/device/MqttEditorDialog.vue'
  import SingleDeviceDialog from './comps/device/SingleDeviceDialog.vue'
  import SiteAddDialog from './comps/SiteAddDialog.vue'
  import {UnwrapRef} from "@vue/reactivity";
  import {ElMessage} from "element-plus";
  import {download} from "@/utils/download";
  import {RealtimeType} from '@/utils/deviceConfig' 
  import {loadEnv} from '@/utils/env/'
  const {VITE_FILE_URL} = loadEnv();
  import stomp from "@/variable/Stomp";
  const queryForm: Ref<UnwrapRef<any>> = ref({
    blurry: '',
    page: 0,
    size: 15
  })

  const activeNames = ref([])
  const childNames = ref([])
  const handleColChange = (val: string[]) => {
    console.log(val)
  }

  const showAddDialog = ref(false)
  const showEditorDevice = ref(false)
  const showEditorBase = ref(false)
  const current = ref(0)
  const total = ref(100)
  const dialogTitle = ref("")
  const currentStation = ref({})
  const currentDevice = ref({})

  const close = () => {
    showAddDialog.value = false
  }

  const tableHead = [
    {
      prop: 'name',
      label: '站点名称',
    }, {
      prop: 'lng',
      label: '经度',
      width: '100px'
    }, {
      prop: 'lat',
      label: '纬度',
      width: '100px'
    }
  ]

  let currentSelected

  const search = () => {
    getDatas()
  }

  const onAddStation = () => {
    dialogTitle.value = '添加设备'
    currentStation.value = {}
    showAddDialog.value = true
  }

  const handleSelectionChange = (val) => {
    currentSelected = val
  }
  const onUpgrade = () => {
    let ids
    if (currentSelected && currentSelected.length > 0) {
      ids = []
      currentSelected.forEach(data => {
        ids.push(data.id);
      })
    }
    upgradeDevice(ids)
      .then(resp => {
      })
  }

  let currentProvince = ref({})
  const onBatchUpdate = (item) => {
    showEditorDevice.value = true;
    currentProvince.value = item
  }

  const handleChange = (file) => {
    // let formData = new FormData();
    // formData.append("file", file.raw)
    // uploadExcel(formData)
    uploadExcel(file.raw)
      .then(resp => {
        if (resp.code === 200) {
          ElMessage.success('批量导入成功')
        } else {
          ElMessage.success('批量导入失败')
        }
      })
  }

  const downloadTemp = () => {
    download(`${VITE_FILE_URL}站点模板.xlsx`)
  }


  const getDatas = () => {
    getTree().then(res=>{
      showAddDialog.value = false
    })
  }

  const handleRealtime = (index: number, row: any,command) => {
    let realStatus = row.realStatus?0:1;
    realtimeControl({
      "command":RealtimeType[command],
      "id": row.id,
      "status": realStatus
    }).then(res=>{
      if(res.code===200){
        ElMessage.success('操作成功!')
      }
    })

    // 模拟发生站点在线状态sokect
    // onlineControl({
    //   "command":RealtimeType[command],
    //   "id": row.id,
    //   "status": realStatus
    // }).then(res=>{
    //     debugger
    // }).catch(err=>{
    //   debugger
    // })
  }

  const restart = (index: number, row: any) => {
    reboot({id: row.id})
      .then(resp => {
        if (resp.code == 200) {
          ElMessage.success('重启成功')
        } else {
          ElMessage.error('重启失败')
        }
      })
  }

  const edit = (index: number, row: any) => {
    currentStation.value = row;
    dialogTitle.value = '修改设备信息'
    showAddDialog.value = true
  }

  const editDevice = (index: number, row: any) => {
    currentDevice.value = row;
    showEditorBase.value = true
  }


   const remove =async (index: number, row: any) => {
    await deleteStation({id: row.id})
    await getDatas()
    
    // deleteStation({id: row.id}).then(() => {
    //   getDatas()
    // })
  }
  onMounted(()=>{
    // subscribeTree()
  })

</script>

<style scoped lang="scss">
  @import "@/assets/styles/theme";

  .site-manage {
    text-align: left;
    height: calc(100% - 100px);
    .site-info{
      height: 100%;
      overflow-y: auto;
      background:rgba(6, 175, 175, 0.2);
    }
    :deep(.el-form--inline .el-form-item){
        margin-right: 15px;
    }
  }

  :deep(.el-collapse) {
    --el-collapse-border-color: $table-border-bottom;
    --el-collapse-content-bg-color: $table-background;
    font-size: 15px;
  }

  :deep(.el-collapse-item__header) {
    background-color: $table-background;
    color: $table-color;
    border-bottom: $table-border-bottom;
    padding-left: 10px;
  }

  .dot {
    width: 10px;
    height: 10px;
    border-radius: 5px;
    background: #2c3e50;
    display: inline-block;
    margin-right: 3px;
  }

  .element {
    display: inline-block;
    color: $table-color;
  }
</style>
